package com.atguigu.gulimall.search.search.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.feign.ProductFeignService;
import com.atguigu.gulimall.search.search.MallSearchService;
import com.atguigu.gulimall.search.vo.AttrResponseVo;
import com.atguigu.gulimall.search.vo.BrandVo;
import com.atguigu.gulimall.search.vo.SearchParam;
import com.atguigu.gulimall.search.vo.SearchResult;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.atguigu.gulimall.search.config.GulimallElasticSearchConfigure.COMMON_OPTIONS;

@Service
public class MallSearchServiceImpl implements MallSearchService {
    @Autowired
    RestHighLevelClient client;
    @Autowired
    ProductFeignService productFeignService;
    @Override
    public SearchResult search(SearchParam param) {
        //动态构建出查询需要的DSL语句
        SearchRequest searchRequest = bulidSearchRequest(param);
        SearchResult result = null;
//        SearchResponse result = new SearchResponse(searchRequest, COMMON_OPTIONS.toBuilder())
        //准备检索请求
        try {
            //执行检索请求
            SearchResponse response = client.search(searchRequest, COMMON_OPTIONS);
            //分析响应数据并封装想要的格式
             result =  bulidSearchResult(response,param);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 构建结果数据
     *
     * @param response
     * @param param
     * @return
     */
    private SearchResult bulidSearchResult(SearchResponse response, SearchParam param) {
        SearchResult result = new SearchResult();
        //获取命中信息
        SearchHits hits = response.getHits();
        ArrayList<SkuEsModel> skuEsModels = new ArrayList<SkuEsModel>();
        if (hits.getHits()!=null&&hits.getHits().length>0){
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel model = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (StringUtils.hasText(param.getKeyword())){
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String title = skuTitle.getFragments()[0].string();
                    model.setSkuTitle(title);
                }
                //设置商品信息
                skuEsModels.add(model);
            }
        }
        //当前多有商品涉及到的所以品牌信息
        ArrayList<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms  brandAgg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            String brandId = bucket.getKeyAsString();
            brandVo.setBrandId(Long.parseLong(brandId));
            ParsedStringTerms imgAgg = bucket.getAggregations().get("brand_img_agg");
            String img = imgAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(img);
            ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brand_name_agg");
            String name = brandNameAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(name);
            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);
        //获取商品所有的属性信息
        ArrayList<SearchResult.AttrVo> attrVos = new ArrayList<>();

        ParsedNested attrAgg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            long attrId = bucket.getKeyAsNumber().longValue();
            ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attr_name_agg");
            String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrName);
            ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attr_value_agg");
            List<String> attrValue = attrValueAgg.getBuckets().stream().map(item -> {
                return item.getKeyAsString();
            }).collect(Collectors.toList());
            attrVo.setAttrValue(attrValue);
            attrVos.add(attrVo);

        }

        result.setAttrs(attrVos);
        //设置分类聚合信息
        ParsedLongTerms catalogAgg = response.getAggregations().get("catalog_agg");
        ArrayList<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        for (Terms.Bucket bucket : catalogAgg.getBuckets()) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            String keyAsString = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(keyAsString));
            ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");
            String keyAsString1 = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(keyAsString1);
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);
        //分页信息-页码
        result.setPageNum(param.getPageNum());
        //分页信息-总记录数
        long total = hits.getTotalHits().value;
        result.setTatal(total);
        int totalPages =  total%EsConstant.PRODUCT_PAGESIZE == 0?(int) total/EsConstant.PRODUCT_PAGESIZE:(int)(total/EsConstant.PRODUCT_PAGESIZE)+1;
        result.setTotalPages(totalPages);

        result.setSkuEsModels(skuEsModels);
        ArrayList<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);
        if (param.getAttrs()!=null&&param.getAttrs().size()>0) {
            List<SearchResult.NavVo> collect = param.getAttrs().stream().map(item -> {
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                String[] s = item.split("_");
                navVo.setNavValue(s[1]);
                result.getAttrIds().add(Long.parseLong(s[0]));

                R r = productFeignService.attrinfo(Long.parseLong(s[0]));
                if (r.getCode() == 0) {
                    AttrResponseVo attr = r.getData("attr", new TypeReference<AttrResponseVo>() {
                    });
                    navVo.setNavName(attr.getAttrName());
                } else {
                    navVo.setNavName(s[0]);
                }
                String replace = this.replaceQueryString(param, item, "attrs");
                navVo.setLink("http://search.mall.com/list.html?" + replace);
                return navVo;
            }).collect(Collectors.toList());
            result.setNavs(collect);
        }
        if (param.getBrandId()!=null&&param.getBrandId().size()>0){
            List<SearchResult.NavVo> navs = result.getNavs();
            SearchResult.NavVo navVo = new SearchResult.NavVo();
            R infos = productFeignService.infos(param.getBrandId());
            if (infos.getCode()==0){
                List<BrandVo> data = infos.getData(new TypeReference<List<BrandVo>>() {});
                StringBuffer buffer = new StringBuffer();
                String replace =null;
                for (BrandVo vo : data) {
                    buffer.append(vo.getBrandName()+";");
                    replace = replaceQueryString(param,param.getBrandId()+"","brandId");
                    navVo.setNavValue("http://search.mall.com/list.html?"+replace);

                }
                navVo.setNavName(buffer.toString());
                navVo.setLink(replace);
            }
            navs.add(navVo);
        }
        return result;
    }

    private static String replaceQueryString(SearchParam param, String item,String key) {
        String encode=null;
        try {
            encode = URLEncoder.encode(item, "UTF-8");
            encode = encode.replace("+","%20");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        String replace = param.get_queryString().replace("&"+key+"="+ encode, "");
        return replace;
    }

    /**
     * 构建请求数据
     * @return
     */
    private SearchRequest bulidSearchRequest(SearchParam param) {
        SearchSourceBuilder source = new SearchSourceBuilder();
        //构建请求
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //must  模糊匹配skuTitle
        if (!StringUtils.isEmpty(param.getKeyword())){
            boolQuery.must(QueryBuilders.matchQuery("skuTitle",param.getKeyword()));
        }
        //fifter 按照三级分类id过滤
        if (param.getCatalog3Id()!=null){
            boolQuery.filter(QueryBuilders.termQuery("catalogId",param.getCatalog3Id()));
        }
        //按照品牌id查询
        if (param.getBrandId()!=null&&param.getBrandId().size()>0){
            boolQuery.filter(QueryBuilders.termsQuery("brandId",param.getBrandId()));
        }
        //按照所有指定的属性进行查询
        if (param.getAttrs()!=null&&param.getAttrs().size()>0){
            for (String attr : param.getAttrs()) {
                String[] s = attr.split("_");
                String attrId = s[0];
                String[] attrValues = s[1].split(":");
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue",attrValues));
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }
        //按照是否有库存进行查询
        if (param.getHasStock()!=null){
            boolQuery.filter(QueryBuilders.termQuery("hasStock",param.getHasStock()==1));
        }
        //按照价格区间进行查询
        if (param.getSkuPrice()!=null){
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String skuPrice = param.getSkuPrice();
            String[] s = skuPrice.split("_");
            if (s.length==2){
                rangeQuery.gte(s[0]).lte(s[1]);
            }
            if (skuPrice.startsWith("_")){
                rangeQuery.lte(s[0]);
            }
            if (skuPrice.endsWith("_")){
                rangeQuery.gte(s[0]);
            }
            boolQuery.filter(rangeQuery);
        }
        //排序
        if (StringUtils.hasText(param.getSort())){
            String[] s = param.getSort().split("_");
            SortOrder order = s[1].equalsIgnoreCase("asc")?SortOrder.ASC:SortOrder.DESC;
            source.sort(s[0],order);
        }
        source.query(boolQuery);
        //分页
        source.from((param.getPageNum()-1)*EsConstant.PRODUCT_PAGESIZE);
        source.size(EsConstant.PRODUCT_PAGESIZE);
        //高亮
        if (StringUtils.hasText(param.getKeyword())){
            HighlightBuilder builder = new HighlightBuilder();
            builder.field("skuTitle");
            builder.preTags("<b style='color:red'>");
            builder.postTags("</b>");
            source.highlighter(builder);
        }
        //聚合分析
        //聚合品牌信息
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        source.aggregation(brand_agg);
        //分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg");
        catalog_agg.field("catalogId").size(20);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        source.aggregation(catalog_agg);
        //属性聚合
        //1.聚合属性attr_agg`
        NestedAggregationBuilder nested = AggregationBuilders.nested("attr_agg", "attrs");
        //2.聚合出当前所有的attrid
        TermsAggregationBuilder attrIdAgg =AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        nested.subAggregation(attrIdAgg);
        //3.聚合分析出attr_id对应的名字
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        //4.聚合分析出当前attr_id 对应的所有可能的属性值attraValue
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        source.aggregation(nested);
        SearchRequest request = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, source);
        String string = source.toString();
        System.out.println("构建的DSL"+string);
        return request;
    }
}
